package com.controller.interceptor;

import com.controller.security.Idempotent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.service.IdempotentService;
import com.service.exception.IdempotentException;
import com.vo.ResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class IdempotentInterceptor implements HandlerInterceptor {
    @Autowired
    private IdempotentService idempotentService;

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;

        Method method = handlerMethod.getMethod();

        Idempotent annotation = method.getAnnotation(Idempotent.class);

        //就表示有幂等性的要求
        if(annotation!=null){
            String token = request.getHeader("token");
            try {
                return idempotentService.validateToken(token);
            }catch (IdempotentException ie){

                ResponseVO<String> responseVO = new ResponseVO<>(10001, "重复性操作", null);
                String responseVOJson = objectMapper.writeValueAsString(responseVO);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(responseVOJson);
                return false;
            }
        }

        return true;
    }

}
